﻿using System;
using System.Web.Security;
using PegasCompany.Data;
using PegasCompany.Tools;

namespace PegasCompany.SiteMembership
{
	public class UserRepository
	{
		public MembershipUser CreateUser(string username, string password, string email, bool isActivated)
		{
			string sPasswordSalt = CryptoHelper.CreateSalt();

			SiteUser user = new SiteUser
								{
									Email = email,
									Password = CryptoHelper.CreatePasswordHash(password, sPasswordSalt),
									PasswordSalt = sPasswordSalt,
									IsActivated = isActivated
								};
			user.Save();

			return GetUser(username);
		}

		public bool ActivateUser(string email, string key)
		{
			SiteUser dbuser = SiteUser.SearchByEmail(email);
			if (dbuser != null)
			{
				if (dbuser.NewEmailKey == key)
				{
					dbuser.IsActivated = true;
					dbuser.NewEmailKey = null;

					dbuser.UpdateInstance();
					return true;
				}
				return false;
			}
			return false;
		}

		public MembershipUser GetUser(string email)
		{
			SiteUser dbuser = SiteUser.SearchByEmail(email);

			if (dbuser != null && dbuser.UserId != null && dbuser.IsActivated != null && dbuser.IsLockedOut != null && dbuser.CreatedDate != null && dbuser.LastLoginDate != null && dbuser.LastLockedOutDate != null)
			{
				int providerUserKey = dbuser.UserId.Value;
				string passwordQuestion = string.Empty;
				string comment = dbuser.Comments;
				bool isApproved = dbuser.IsActivated.Value;
				bool isLockedOut = dbuser.IsLockedOut.Value;
				DateTime creationDate = dbuser.CreatedDate.Value;
				DateTime lastLoginDate = dbuser.LastLoginDate.Value;
				DateTime lastActivityDate = DateTime.Now;
				DateTime lastPasswordChangedDate = DateTime.Now;
				DateTime lastLockedOutDate = dbuser.LastLockedOutDate.Value;

				MembershipUser user = new MembershipUser("HmtMembershipProvider",
														 email,
														 providerUserKey,
														 email,
														 passwordQuestion,
														 comment,
														 isApproved,
														 isLockedOut,
														 creationDate,
														 lastLoginDate,
														 lastActivityDate,
														 lastPasswordChangedDate,
														 lastLockedOutDate);

				return user;
			}
			return null;
		}
	}
}